<?php

namespace app\system\controller\customer;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use ba\Filesystem;
use hehe\Arr;
use hehe\Numeral;
use hehe\Str;
use hehe\Trade;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use think\facade\Config;
use think\facade\Db;


class Order extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['out_trade_no', 'contract'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\customer\Order;
    }

    /**
     * 下载报关文件
     */
    public function download(){
        $param = $this->request->param();
        if(empty($param['enterprise'])) $this->error(__('请选择报关企业'));
        if(empty($param['checkedType'])) $this->error(__('请选择您要下载的文件'));


        $enterprise = strtoupper($param['enterprise']);



        $all = [
            'invoice', 'packing_list', 'commercial_invoice', 'customer_contract', 'baoguandan', 'element'
        ];
        $diff = array_diff($all, $param['checkedType']);

//        print_r($diff);die;




        $customer = $param['ids'][0]['customer']; // 客户资料
        $order_time = $param['ids'][0]['create_time']; // 下单时间
        $contract = $param['ids'][0]['contract']; // 合同号
        $exchange = $param['ids'][0]['exchange']; // 汇率
        $shipment = $param['ids'][0]['shipment']; // 运输方式
        $deal_type = $param['ids'][0]['deal_type']; // 成交方式

        $date = date('ymdHis', $this->timestamp);

        $from_path = Filesystem::fsFit(public_path() . 'static/file_template/baoguan_' . $param['enterprise'] . '.xlsx');
        $to_path = Filesystem::fsFit(public_path() . 'storage/baoguan');

        if(!is_dir($to_path)) Filesystem::mkdir($to_path);

        $to_path .= Filesystem::fsFit("/{$enterprise}报关资料{$date}.xlsx");

        // 加载Excel文件
        $spreadsheet = IOFactory::load($from_path);

        $product = [];
        foreach($param['ids'] as $val){
            $res = db::name('customer_order_detail')->alias('d')
                ->leftJoin('product p', 'p.id = d.product_id')
                ->leftJoin('product_category c', 'c.id = p.category_id')
                ->where(['d.order_id' => $val['id']])
                ->field('d.order_id, d.product_id, d.quantity, c.name_cn category_name_cn, 
                c.name_en category_name_en, c.hs_code, c.element, c.unit, p.category_id,
                p.name product_name, p.code product_code, p.buy_price, p.buy_currency, 
                p.sale_price, p.sale_currency')
                ->order('d.id asc')->select()->toArray();
            foreach($res as $v){
                $v['quantity'] /= $this->multiply;
                $v['buy_price'] /= $this->multiply;
                $v['sale_price'] /= $this->multiply;
                $product['category_' . $v['category_id']][] = $v;
            }
        }

//        print_r($product);die;



        foreach($diff as $val){
            $sheetNames = $spreadsheet->getSheetNames(); // 所有的工作表
            if($val == 'packing_list'){ // 箱单
                $sheetIndex = array_search('PACKING LIST', $sheetNames);
                $spreadsheet->removeSheetByIndex($sheetIndex);
            }

            if($val == 'customer_contract'){ // 客户合同
                $sheetIndex = array_search('CONTRACT', $sheetNames);
                $spreadsheet->removeSheetByIndex($sheetIndex);
            }


            if($val == 'element'){ // 申报要素
                $sheetIndex = array_search('申报要素', $sheetNames);
                $spreadsheet->removeSheetByIndex($sheetIndex);
            }

            if($val == 'baoguandan'){ // 报关单
                $sheetIndex = array_search('报关单', $sheetNames);
                $spreadsheet->removeSheetByIndex($sheetIndex);
            }

            if($val == 'invoice'){ // 发票
                $sheetIndex = array_search('INVOICE', $sheetNames);
                $spreadsheet->removeSheetByIndex($sheetIndex);
            }

            if($val == 'commercial_invoice'){ // CI
                $sheetIndex = array_search('COMMERCIAL INVOICE', $sheetNames);
                $spreadsheet->removeSheetByIndex($sheetIndex);
            }
        }


        foreach($param['checkedType'] as $val){
            if($val == 'packing_list'){ // 箱单
                $sheet = $spreadsheet->getSheetByName('PACKING LIST');
                $sheet->setCellValue('C4', date('Y-m-d', $order_time));
                $sheet->setCellValue('C5', 'China');
                $sheet->setCellValue('G4', $contract);
                $sheet->setCellValue('G5', $contract);

                if(count($product) > 1){
                    $sheet->insertNewRowBefore(11, count($product) - 1);
                    for($i = 0; $i < count($product); $i++){
                        $index = 11 + $i;
                        $sheet->mergeCells("B{$index}:C{$index}"); // 合并单元格
                    }
                }
                $row = 10;
                $no = 1;
                $quantity_count = 0;
                foreach($product as $v){
                    $sheet->setCellValue("A{$row}", $no);
                    $sheet->setCellValue("B{$row}", $v[0]['category_name_en']);
                    $quantity = 0;
                    foreach($v as $vs){
                        $quantity += $vs['quantity'];
                    }
                    $quantity_count += $quantity;
                    $sheet->setCellValue("D{$row}", $quantity);
                    $sheet->setCellValue("E{$row}", $v[0]['unit']);
                    $row++;
                    $no++;
                }
                $sheet->setCellValue("D{$row}", $quantity_count);
                $row += 3;
                $sheet->setCellValue("C{$row}", $customer['corp_name_en']);
                $row++;
                $sheet->setCellValue("C{$row}", $customer['address']);
                $row++;
                $sheet->setCellValue("C{$row}", $customer['contact']);
            }

            if($val == 'customer_contract'){ // 客户合同
                $sheet = $spreadsheet->getSheetByName('CONTRACT');
                $sheet->setCellValue('C4', 'WHYNOT COMPANY(SUZHOU) CO., LTD.');
                $sheet->setCellValue('C5', $customer['corp_name_en']);
                $sheet->setCellValue('G4', date('Y-m-d', $order_time));
                $sheet->setCellValue('G5', $contract);

                if(count($product) > 1){
                    $sheet->insertNewRowBefore(11, count($product) - 1);
                    for($i = 0; $i < count($product); $i++){
                        $index = 11 + $i;
                        $sheet->mergeCells("B{$index}:C{$index}"); // 合并单元格
                    }
                }
                $row = 10;
                $no = 1;
                $quantity_count = 0;
                $sale_price_all_count = 0;
                foreach($product as $v){
                    $sheet->setCellValue("A{$row}", $no);
                    $sheet->setCellValue("B{$row}", $v[0]['category_name_en']);
                    $quantity = 0;
                    $sale_price_count = 0; // 销售价格 全部
                    $product_count = 0; // 商品数量
                    foreach($v as $vs){
                        $quantity += $vs['quantity'];
                        $sale_price_count += $vs['sale_price'];
                        $product_count++;
                    }
                    $quantity_count += $quantity;
                    $amount = $sale_price_count / $product_count;
                    $amount_count = $sale_price_count * $quantity;
                    $sale_price_all_count += $amount_count;
                    $sheet->setCellValue("D{$row}", $quantity);
                    $sheet->setCellValue("E{$row}", $v[0]['unit']);
                    $sheet->setCellValue("F{$row}", $amount);
                    $sheet->setCellValue("G{$row}", $amount_count);
                    $row++;
                    $no++;
                }
                $sheet->setCellValue("D{$row}", $quantity_count);
                $sheet->setCellValue("G{$row}", $sale_price_all_count);
                $row += 3;
                $sheet->setCellValue("C{$row}", $customer['corp_name_en']);
                $row++;
                $sheet->setCellValue("C{$row}", $customer['address']);
                $row++;
                $sheet->setCellValue("C{$row}", $customer['contact']);
            }


            if($val == 'element'){ // 申报要素
                $sheet = $spreadsheet->getSheetByName('申报要素');
                $row = 2;
                foreach($product as $v){
                    $sheet->setCellValue("A{$row}", $v[0]['hs_code'] . '(' . $v[0]['category_name_cn'] . ')');
                    $row++;
                    $element = $v[0]['element'];
                    $element = empty($element) ? [] : explode("\n", $element);
                    foreach($element as $vs){
                        $sheet->setCellValue("A{$row}", $vs);
                        $row++;
                    }
                    $row++;
                }
            }

            if($val == 'baoguandan'){ // 报关单
                $sheet = $spreadsheet->getSheetByName('报关单');
                $sheet->setCellValue('A6', $customer['corp_name_en']);
                $sheet->setCellValue('A10', $contract);
                $sheet->setCellValue('H12', $deal_type);
                $sheet->setCellValue('C6', $shipment);

                if(count($product) > 1){
                    $sheet->insertNewRowBefore(19, count($product) - 1);
                    for($i = 0; $i < count($product); $i++){
                        $index = 19 + $i;
                        $sheet->mergeCells("C{$index}:D{$index}"); // 合并单元格
                        $sheet->mergeCells("H{$index}:I{$index}"); // 合并单元格
                        $sheet->mergeCells("L{$index}:M{$index}"); // 合并单元格
                    }
                }
                $row = 18;
                $no = 1;
                $quantity_count = 0;
                $sale_price_all_count = 0;
//                print_r($product);die;
                foreach($product as $v){
                    $sheet->setCellValue("A{$row}", $no);
                    $sheet->setCellValue("B{$row}", $v[0]['hs_code']);
                    $sheet->setCellValue("C{$row}", $v[0]['category_name_cn']);
                    $quantity = 0;
                    $sale_price_count = 0; // 销售价格 全部
                    $product_count = 0; // 商品数量
                    foreach($v as $vs){
                        $quantity += $vs['quantity'];
                        $sale_price_count += $vs['sale_price'];
                        $product_count++;
                    }
                    $quantity_count += $quantity;
                    $amount = $sale_price_count / $product_count;
                    $amount_count = $sale_price_count * $quantity;
                    $sale_price_all_count += $amount_count;
                    $sheet->setCellValue("E{$row}", $quantity);
                    $sheet->setCellValue("F{$row}", $v[0]['unit']);
                    $sheet->setCellValue("G{$row}", $amount);
                    $sheet->setCellValue("H{$row}", $amount_count);
                    $sheet->setCellValue("J{$row}", 'USD');
                    $sheet->setCellValue("K{$row}", '中国');
                    $row++;
                    $no++;
                }
            }

            if($val == 'invoice'){ // 发票
                // 获取工作表
                $sheet = $spreadsheet->getSheetByName('INVOICE');
                $sheet->setCellValue('B5', $customer['corp_name_en']);
                $sheet->setCellValue('B6', $customer['address']);
                $sheet->setCellValue('B7', $customer['contact']);
                $sheet->setCellValue('B8', $customer['email']);
                $sheet->setCellValue('E5', date('Y-m-d', $order_time));
                $sheet->setCellValue('E6', $contract);
                $sheet->setCellValue('E7', $exchange);
                $sheet->setCellValue('A11', "Shipment : Transport By {$shipment}");
                $sheet->setCellValue('A12', "Destination : {$customer['area']} (Zip Code: {$customer['zip_code']})");
                $sheet->setCellValue('A13', "Departure point : China");
                if(count($product) > 1){
                    $sheet->insertNewRowBefore(20, count($product) - 1);
                    for($i = 0; $i < count($product); $i++){
                        $index = 20 + $i;
                        $sheet->mergeCells("B{$index}:C{$index}"); // 合并单元格
                    }
                }
                $row = 19;
                $no = 1;
                $quantity_count = 0;
                $sale_price_all_count = 0;
                foreach($product as $v){
                    $sheet->setCellValue("A{$row}", $no);
                    $sheet->setCellValue("B{$row}", $v[0]['category_name_en']);
                    $quantity = 0;
                    $sale_price_count = 0; // 销售价格 全部
                    $product_count = 0; // 商品数量
                    foreach($v as $vs){
                        $quantity += $vs['quantity'];
                        $sale_price_count += $vs['sale_price'];
                        $product_count++;
                    }
                    $quantity_count += $quantity;
                    $amount = $sale_price_count / $product_count;
                    $amount_count = $sale_price_count * $quantity;
                    $sale_price_all_count += $amount_count;
                    $sheet->setCellValue("D{$row}", $quantity);
                    $sheet->setCellValue("E{$row}", $v[0]['unit']);
                    $sheet->setCellValue("F{$row}", $amount);
                    $sheet->setCellValue("G{$row}", $amount_count);
                    $row++;
                    $no++;
                }
                $sheet->setCellValue("D{$row}", $quantity_count);
                $sheet->setCellValue("G{$row}", $sale_price_all_count);
            }

            if($val == 'commercial_invoice'){ // CI
                // 获取工作表
                $sheet = $spreadsheet->getSheetByName('COMMERCIAL INVOICE');
                $sheet->setCellValue('B5', $customer['corp_name_en']);
                $sheet->setCellValue('B6', $customer['address']);
                $sheet->setCellValue('B7', $customer['contact']);
                $sheet->setCellValue('E5', date('Y-m-d', $order_time));
                $sheet->setCellValue('E6', $contract);
                $sheet->setCellValue('E7', $customer['email']);

                $sheet->setCellValue('A10', "Shipment : Transport By {$shipment}");
                $sheet->setCellValue('A11', "Destination : {$customer['area']} (Zip Code: {$customer['zip_code']})");
                $sheet->setCellValue('A12', "Departure point : China");
                if(count($product) > 1){
                    $sheet->insertNewRowBefore(19, count($product) - 1);
                    for($i = 0; $i < count($product); $i++){
                        $index = 19 + $i;
                        $sheet->mergeCells("B{$index}:D{$index}"); // 合并单元格
                    }
                }
                $row = 18;
                $no = 1;
                $quantity_count = 0;
                $sale_price_all_count = 0;
                foreach($product as $v){
                    $sheet->setCellValue("A{$row}", $no);
                    $sheet->setCellValue("B{$row}", $v[0]['category_name_en']);
                    $quantity = 0;
                    $sale_price_count = 0; // 销售价格 全部
                    $product_count = 0; // 商品数量
                    foreach($v as $vs){
                        $quantity += $vs['quantity'];
                        $sale_price_count += $vs['sale_price'];
                        $product_count++;
                    }
                    $quantity_count += $quantity;
                    $amount = $sale_price_count / $product_count;
                    $amount_count = $sale_price_count * $quantity;
                    $sale_price_all_count += $amount_count;
                    $sheet->setCellValue("E{$row}", $quantity);
//                    $sheet->setCellValue("E{$row}", $v[0]['unit']);
                    $sheet->setCellValue("F{$row}", $amount);
                    $sheet->setCellValue("G{$row}", $amount_count);
                    $row++;
                    $no++;
                }
                $sheet->setCellValue("E{$row}", $quantity_count);
                $sheet->setCellValue("G{$row}", $sale_price_all_count);
            }
        }



        // 保存修改后的Excel文件
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); // 保存为Excel 2007及以上版本的文件
        $writer->save($to_path); // 修改为你想保存的文件名



        $file_url = '/storage/baoguan' . "/{$enterprise}报关资料{$date}.xlsx";
        $this->success('', [
            'type' => 'download',
            'file_url' => $file_url
        ]);


    }


    public function updateField(){
        $params = $this->request->param();
        $result = db::name('customer_order')->where(['id' => $params['id']])->update([$params['field'] => $params['new_value'], 'update_time' => $this->timestamp]);
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 下载供货商合同
     */
    public function ckGenerateHt(){
        $order_id = $this->request->param('order_id');
        $order = db::name('customer_order')->where(['id' => $order_id])->find();
        $supplier_id = $order['supplier_id'];
        $order_time = $order['create_time'];

        $list = db::name('customer_order_detail')->where('order_id', $order_id)->select()->toArray();
        $category_names = [];
        foreach($list as $key => $val){
            $product = db::name('product')->where(['id' => $val['product_id']])->find();
            $list[$key]['code'] = $product['code'];
            $list[$key]['name'] = $product['name_customer'];
            $list[$key]['drawing_image'] = $product['drawing_image'];
            $category = db::name('product_category')->where(['id' => $product['category_id']])->find();

            if(!in_array($category['name_cn'], $category_names)) $category_names[] = $category['name_cn'];


            $list[$key]['unit'] = $category['unit'];
            $list[$key]['quantity'] = $val['quantity'] / $this->multiply;
        }
        $category_names = implode('&', $category_names);
        $res = $this->generateHt($supplier_id, $order_time, $category_names, $list);
        $this->success('success', $res);
    }

    /**
     * 生成供货商合同
     * @param $supplier_id @供货商id
     * @param $order_time @下单时间
     * @param $category_names @产品分类
     * @param $list @产品列表
     */
    public function generateHt($supplier_id, $order_time, $category_names, $list){


        $source_file = Filesystem::fsFit(public_path() . 'static/file_template/ht.xlsx');
        $save_path = Filesystem::fsFit(public_path() . 'storage/generate');

        $supplier = db::name('supplier')->where(['id' => $supplier_id])->find();

        if(!is_dir($save_path)) Filesystem::mkdir($save_path);
        $date = date('ymd', $order_time);
        $file_name = "{$supplier['short_name_cn']}&哇衣娜({$category_names})-{$date}.xlsx";
        $save_path .= Filesystem::fsFit("/{$file_name}");

        // 加载Excel文件
        $spreadsheet = IOFactory::load($source_file);
        // 获取活动工作表
        $sheet = $spreadsheet->getActiveSheet();


//        print_r($supplier);die;

        // 设置单元格内容
        $sheet->setCellValue('B3', $supplier['corp_name_cn']);
        $sheet->setCellValue('F3', date('Y.m.d', $order_time));
        $sheet->setCellValue('F4', "YN{$date}{$supplier['short_name_en']}");


        // 生成产品信息列表
        $row = 8;
        $product_num = count($list);
        if($product_num > 1){
            $sheet->insertNewRowBefore($row + 1, $product_num - 1);
        }

        foreach($list as $key => $val){
            // 设置序号
            $sheet->setCellValue('A' . $row, '=ROW()-7');
            // 填写产品名
            $sheet->setCellValue('B' . $row, $val['code'] . "\n" . $val['name']);
            // 设置单元格文字水平和垂直居中
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                ],
            ];
            // 设置单元格自动换行
            $sheet->getStyle('B' . $row)->getAlignment()->setWrapText(true);
            // 设置某行的高度自适应内容
            $sheet->getRowDimension($row)->setRowHeight(-1);


            $sheet->getStyle('B' . $row)->applyFromArray($styleArray);
            // 填写数量
            $sheet->setCellValue('C' . $row, $val['quantity']);
            // 填写单位
            $sheet->setCellValue('D' . $row, $val['unit']);
            // 填写单价

            // 填写总价
            $sheet->setCellValue('F' . $row, "=C{$row}*E{$row}");

//            Drawing::
            // 创建一个 Drawing 对象, 添加图纸
            $drawing = new Drawing();
            // 设置图片路径
            $drawing->setPath(public_path() . $val['drawing_image']);
            // 设置图片要插入的单元格
            $drawing->setCoordinates('G' . $row);
            // 设置图片在单元格内水平居中
//            $drawing->setHorizontalAlignment(Drawing::HORIZONTAL_ALIGNMENT_CENTER);
            // 设置图片在单元格内垂直居中
//            $drawing->setVerticalAlignment(Drawing::VERTICAL_ALIGNMENT_CENTER);
            // 设置图片宽度和高度（可选）
            // 获取单元格的宽度和高度（这里简单假设单元格宽度和高度固定，实际情况可能需要根据列宽和行高计算）
            $cellWidth = 130;
            $cellHeight = 30;
            // 获取图片的宽度和高度
            $imageWidth = 130;
            $imageHeight = 30;
            // 计算水平和垂直偏移量以实现居中
            $offsetX = ($cellWidth - $imageWidth) / 2;
            $offsetY = ($cellHeight - $imageHeight) / 2;
            // 设置偏移量
            $drawing->setOffsetX($offsetX);
            $drawing->setOffsetY($offsetY);
            // 设置图片宽度和高度
            $drawing->setWidth($imageWidth);
            $drawing->setHeight($imageHeight);
            // 将图片添加到工作表中
            $drawing->setWorksheet($sheet);

            //自增行数
            $row++;
        }
        $end_row = $row - 1;
        $sheet->setCellValue('C' . $row, "=SUM(D8:D{$end_row})");
        $sheet->setCellValue('F' . $row, "=SUM(G8:G{$end_row})");

        $row += 11;
        $sheet->setCellValue('B' . $row++, $supplier['corp_name_cn']); // 公司名
        $sheet->setCellValue('B' . $row++, $supplier['address']); // 公司地址
        $sheet->setCellValue('B' . $row++, $supplier['manager']); // 委托代理人姓名
        $sheet->setCellValue('B' . $row++, $supplier['tel']); // 代理人电话
        $sheet->setCellValue('B' . $row++, $supplier['bank_address']); // 开户行

        $sheet->getCell('B' . $row++)->setValueExplicit($supplier['bank_number'], DataType::TYPE_STRING); // 账号
        $sheet->getCell('B' . $row)->setValueExplicit($supplier['bank_code'], DataType::TYPE_STRING); // 行号



        // 保存修改后的Excel文件
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); // 保存为Excel 2007及以上版本的文件
        $writer->save($save_path); // 修改为你想保存的文件名
        return '/storage/generate/' . $file_name;
    }


    public function ckGeneratePi(){
        $order_id = $this->request->param('order_id');
        $order = db::name('customer_order')->where(['id' => $order_id])->find();
        $customer_id = $order['customer_id'];
        $order_time = $order['create_time'];
        $exchange = $order['exchange'];
        $order_all = db::name('customer_order')->field('id')->where(['out_trade_no' => $order['out_trade_no']])->select()->toArray();
        $order_ids = [];
        foreach($order_all as $val){
            $order_ids[] = $val['id'];
        }
        $list = db::name('customer_order_detail')->whereIn('order_id', $order_ids)->select()->toArray();
        foreach($list as $key => $val){
            $product = db::name('product')->where(['id' => $val['product_id']])->find();
            $list[$key]['code'] = $product['code'];
            $list[$key]['name'] = $product['name_customer'];
            $category = db::name('product_category')->where(['id' => $product['category_id']])->find();
            $list[$key]['unit'] = $category['unit'];
            $list[$key]['quantity'] = $val['quantity'] / $this->multiply;
        }
        $res = $this->generatePi($customer_id, $order_time, $exchange, $list);
        $this->success('success', $res);
    }

    /**
     * 生成pi
     * @param $customer_id 客户id
     * @param $order_time 下单时间
     * @param $exchange 汇率
     * @param $list 产品列表
     */
    public function generatePi($customer_id, $order_time, $exchange, $list){
        $source_file = Filesystem::fsFit(public_path() . 'static/file_template/pi.xlsx');
        $save_path = Filesystem::fsFit(public_path() . 'storage/generate');

        $sign_data = Config::get('options.sign_data');
        $sign_data = $sign_data[$customer_id];

        if(!is_dir($save_path)) Filesystem::mkdir($save_path);
        $date = date('ymd', $order_time);
        $file_name = "{$sign_data['file_name']} PI-{$date}.xlsx";
        $save_path .= Filesystem::fsFit("/{$file_name}");

        // 加载Excel文件
        $spreadsheet = IOFactory::load($source_file);
        // 获取活动工作表
        $sheet = $spreadsheet->getActiveSheet();


//        print_r($sign_data);die;

        // 设置单元格内容
        $sheet->setCellValue('B5', $sign_data['company_name']);
        $sheet->setCellValue('B6', $sign_data['address']);
        $sheet->setCellValue('B7', $sign_data['tel']);
        $sheet->setCellValue('B8', $sign_data['email']);
        $sheet->setCellValue('A12', $sign_data['destination']);
        $sheet->setCellValue('E5', date('Y.m.d', $order_time));
        $sheet->setCellValue('E6', 'YN' . date('ymd', $order_time));
        $sheet->setCellValue('E7', $exchange);

        // 生成产品信息列表
        $row = 19;
        $product_num = count($list);
        if($product_num > 1){
            $sheet->insertNewRowBefore($row + 1, $product_num - 1);
        }

        foreach($list as $key => $val){
            // 合并单元格
            $sheet->mergeCells("B{$row}:C{$row}");
            // 设置序号
            $sheet->setCellValue('A' . $row, '=ROW()-18');
            // 填写产品名
            $sheet->setCellValue('B' . $row, $val['code'] . "\n" . $val['name']);
            // 设置单元格文字水平和垂直居中
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                ],
            ];
            $sheet->getStyle('B' . $row)->applyFromArray($styleArray);
            // 填写数量
            $sheet->setCellValue('D' . $row, $val['quantity']);
            // 填写单位
            $sheet->setCellValue('E' . $row, $val['unit']);
            // 填写单价

            // 填写总价
            $sheet->setCellValue('G' . $row, "=D{$row}*F{$row}");

            //自增行数
            $row++;
        }
        $end_row = $row - 1;
        $sheet->setCellValue('D' . $row, "=SUM(D19:D{$end_row})");
        $sheet->setCellValue('G' . $row, "=SUM(G19:G{$end_row})");


        // 保存修改后的Excel文件
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); // 保存为Excel 2007及以上版本的文件
        $writer->save($save_path); // 修改为你想保存的文件名
        return '/storage/generate/' . $file_name;
    }

    /**
     * 批量生成订单
     */
    public function batch(){
        $params = $this->request->param();
        if(empty($params['type'])) $this->error(__('请选择') . __('订单类型'));
        if(empty($params['file'])) $this->error(__('请上传订单文件'));
        $filePath = Filesystem::fsFit(public_path() . $params['file']);
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getSheet(0);
        $content = $sheet->toArray(); // 获取表格中的文字内容
        if(empty($content)) $this->error(__('Excel数据获取失败'));
        unset($content[0]);
        unset($content[1]);
//        print_r($content);die;

        $params['create_time'] = strtotime($params['create_time']);

        $list = [];
        $unit_column = 0; // 获取单位列，依据单位列获得数量列所在位置
        $customer_id = 0; // 客户id
        foreach($content as $key => $val){

            if(!empty($val[3])){
                if($val[1] == 'GROUP'){
                    foreach($val as $k => $v){
                        if($v == 'Unit'){
                            $unit_column = $k;
                        }
                    }
                    continue;
                }
                $quantity = Numeral::restoreNumberFormat($val[$unit_column - 1]);
                if($quantity <= 0){
                    continue;
                }
                $list[] = [
                    'code' => $val[2],
                    'name' => $val[3],
                    'quantity' => $quantity,
                    'file_row' => $key + 1,
                ];
            }
        }
//        print_r($list);die;
        $category_ids = [];
        foreach($list as $key => $val){
            $res = db::name('product')->field('id, category_id, name_customer name, code')->where(['code' => $val['code']])->select()->toArray();
            if(empty($res)) $this->error("文件第{$val['file_row']}行产品编码：{$val['code']} 在系统中没有记录，请将该产品录入系统");
            if(count($res) > 1) $this->error("文件第{$val['file_row']}行产品编码：{$val['code']} 在系统中重复，请修正系统中的记录");
//            print_r($res);die;
            $list[$key]['product_id'] = $res[0]['id'];
            $list[$key]['category_id'] = $res[0]['category_id'];
            if(!in_array($res[0]['category_id'], $category_ids)) $category_ids[] = $res[0]['category_id'];
        }
        $category = [];
        $supplier_ids = [];
        foreach($category_ids as $val){
            $res = db::name('product_category')->field('id, supplier_id, customer_id, name_cn, name_en, unit')->where(['id' => $val])->find();
            $category[] = $res;
            if($customer_id == 0) $customer_id = $res['customer_id'];
        }
        foreach($category as $val){
            foreach($list as $k => $v){
                if($val['id'] == $v['category_id']){
                    $list[$k]['supplier_id'] = $val['supplier_id'];
                    if(!in_array($val['supplier_id'], $supplier_ids)){
                        $supplier_ids[] = $val['supplier_id'];
                    }
                    $list[$k]['unit'] = $val['unit'];
                }
            }
        }
//        print_r($category);

//        print_r($params);
//         print_r($list);die;






        $contract = 'YN' . date('ymd', $params['create_time']);

        $customer_deal_type = Config::get('options.customer_deal_type'); // 成交方式，如：FOB/CIF/EXW

        // 生成pi
//        $generate_pi = $this->generatePi($customer_id, $params['create_time'], $list);
//        var_dump($generate_pi); die;


        db::startTrans();
        try{

            $order_trade_no = Trade::generateTradeNoShort();
            foreach($supplier_ids as $key => $val){

                $deal_type = empty($customer_deal_type[$key]) ? null : $customer_deal_type[$key]; // 成交方式，如：FOB/CIF/EXW

                $order_insert = [
                    'filter_id' => $this->filter['id'], // 子站点id
                    'out_trade_no' => $order_trade_no, // 系统订单号
                    'contract' => $contract, // 合同编号
                    'customer_id' => $customer_id, // 客户id
                    'supplier_id' => $val, // 供货商id
                    'trade_type' => $params['type'][1], // 订单类型1
                    'order_type' => $params['type'][0], // 订单类型2
                    'create_time' => $params['create_time'], // 下单时间
                    'deal_type' => $deal_type, // 成交方式，如：FOB/CIF/EXW
                    'note' => '批量生成',
                    'exchange' => $params['exchange']
                ];
                $order_id = db::name('customer_order')->insertGetId($order_insert);
                $list_insert = [];
                foreach($list as $v){

                    if($val == $v['supplier_id']){
                        $list_insert[] = [
                            'order_id' => $order_id,
                            'product_id' => $v['product_id'],
                            'quantity' => $v['quantity'] * $this->multiply,
                            'sale_price' => 0,
                            'sale_currency' => 'USD',
                            'cost_price' => 0,
                            'cost_currency' => 'CNY',
                        ];
                    }
                }
                db::name('customer_order_detail')->insertAll($list_insert);


                // 下面执行远程操作
                $customer_id = $order_insert['customer_id'];
//                print_r($product);die;

            }


            db::commit();
        }catch(\Exception $e){
            db::rollback();
            $this->error($e->getMessage() . ' >>> ' . $e->getLine());
            $this->error($e->getMessage());
        }

        $this->success();
        print_r($product); die;
    }


    /**
     * 处理批量订单文件
     */
    public function batchOrderFile(){
        $params = $this->request->param();
//        print_r($params);die;
        // 读取xls文件内容
        $filePath = Filesystem::fsFit(public_path() . $params['file']);
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getSheet(0);
        $content = $sheet->toArray(); // 获取表格中的文字内容
        if(empty($content[2][0]) || $content[2][0] != '1') $this->error('文件第3行的序号必须从1开始');
        unset($content[0]);
        unset($content[1]);
        $data = [];
        $group = '';
        foreach($content as $val){
            if(strtoupper($val[0]) == 'TOTAL') break;
            $group = empty($val[1]) ? $group : trim($val[1]);
            if($group == '') $this->error('group不能为空');
            $val[1] = $group;
            $data[] = $val;
        }
        foreach($data as $key => $val){
            $group = db::name('customer_product_group')->where(['customer_id' => $params['customer_id'], 'name_en' => $val[1]])->cache(3)->find();
            if(!$group) $this->error('当前客户下不存在group：' . $val[1]);
            $productName = trim($val[3]);
            if(empty($productName)) $this->error('产品名称不能为空');
            $product = db::name('customer_product')->where(['name' => $productName])->find();
            if($product){
                $data[$key]['product'] = $product;
            }else{
                $this->error('当前客户下不存在该产品：' . $productName);
            }
        }

        print_r($data);die;
    }


    /**
     * 拉取订单信息
     */
    public function pull(){
        $params = $this->request->param();
        $out_trade_no = empty($params['out_trade_no']) ? '' : trim($params['out_trade_no']);
        if(empty($params['out_trade_no'])) $this->error(__('请输入订单号'));
        $order = db::name('customer_order')->where(['id' => $params['order_id']])->find();
        if($order['out_trade_no'] == $out_trade_no) $this->error(__('不能拉取相同的订单信息'));
        $pullOrder = db::name('customer_order')->where(['out_trade_no' => $out_trade_no])->find();
        if(!$pullOrder) $this->error(__('请输入正确的订单号'));


        $pullGoods = db::name('customer_order_goods')->where(['order_id' => $pullOrder['id']])->select();
        if($pullGoods){
            $insertGoods = [];
            foreach($pullGoods as $val){
                $insertGoods[] = [
                    'hscode_id' => $val['hscode_id'],
                    'order_id' => $order['id'],
                    'hscode_sku' => $val['hscode_sku'],
                    'name' => $val['name'],
                    'name_en' => $val['name_en'],
                    'cn_origin' => $val['cn_origin'],
                    'country_of_origin' => $val['country_of_origin'],
                    'unit' => $val['unit'],
                    'qty' => $val['qty'],
                    'deal_qty' => $val['deal_qty'],
                    'deal_unit' => $val['deal_unit'],
                    'deal_unit_amount' => $val['deal_unit_amount'],
                    'deal_amount' => $val['deal_amount'],
                    'is_mix' => $val['is_mix'],
                    'pack_qty' => $val['pack_qty'],
                    'gross_weight' => $val['gross_weight'],
                    'net_weight' => $val['net_weight'],
                    'create_time' => $this->timestamp
                ];
            }
            db::name('customer_order_goods')->insertAll($insertGoods);
        }



        $this->success();
    }

    /**
     * 删除代理商
     */
    public function delAgent() {
        $param = $this->request->param();
        $result = db::name('customer_order_agent')->where(['id' => $param['id']])->delete();
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 添加代理商
     */
    public function addAgent(){
        $param = $this->request->param();
        if(empty($param['agent_id'])) $this->error('请选择代理商');
        $order = db::name('customer_order')->where(['id' => $param['order_id']])->find();
        $profit = $order['gross_profit'];
        $insert = [];
        foreach($param['agent_id'] as $val){
            $insert[] = [
                'admin_id' => $this->auth->id,
                'order_id' => $param['order_id'],
                'agent_id' => $val,
                'profit' => $profit,
                'create_time' => $this->timestamp
            ];
        }
        $result = db::name('customer_order_agent')->insertAll($insert);
        if($result){
            $this->success();
        }else{
            $this->error();
        }
        print_r($param);die;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->with(['customer', 'bill', 'supplier', 'detail' => function($detail){
                $detail->with(['product' => function($product){
                    $product->with(['category']);
                }]);
            }])
            ->alias($alias)
            ->where($where)->where(['ba_customer_order.filter_id' => $this->filter['id']]);
        $param = $this->request->param();

        $supplier_where = [];

        if(!empty($param['order_type'])){
            $res = $res->where(['order_type' => $param['order_type']]);
            $supplier_where['order_type'] = $param['order_type'];
        }
        if(!empty($param['invoice_status'])){
            $res = $res->where(['invoice_status' => $param['invoice_status']]);
        }

        if(!empty($param['customer_id'])){
            $res = $res->where(['customer_id' => $param['customer_id']]);
            $supplier_where['customer_id'] = $param['customer_id'];
        }
        if(!empty($param['supplier_id'])){
            $res = $res->where(['supplier_id' => $param['supplier_id']]);
        }



        if(!empty($param['create_time'])){
            $param['create_time'] = date('Y-m-d', strtotime($param['create_time']));
//            print_r($param);die;
//            $param['create_time'] = strtotime($param['create_time']);
            $res = $res->whereDay('ba_customer_order.create_time', $param['create_time']);
        }



//        ['customer.corp_name_cn', 'customer.corp_name_ko', 'customer.manager', 'out_trade_no', 'contract'];
        if(!empty($param['keyword'])){
            $res = $res->whereLike('out_trade_no|note', "%{$param['keyword']}%");
        }

        $res = $res->order('create_time desc, id desc')->paginate($limit);



        $list = $res->items();

        foreach($list as $key => $val){
            $list[$key]['pay_amount'] = $val['pay_amount'] / 100;
            $list[$key]['amount'] = $val['amount'] / 100;
            $list[$key]['cost'] = $val['cost'] / 100; // 货款
            $list[$key]['pay_amount_text'] = Numeral::numberFormat($val['pay_amount']) . ' CNY';
            $list[$key]['amount_text'] = Numeral::numberFormat($val['amount']) . ' CNY';
            $list[$key]['note'] = empty($val['note']) ? '' : html_entity_decode($val['note']);

            $category = [];
            if(!empty($val['detail'])){
                foreach($val['detail'] as $detail){
                    if(!empty($detail['product']['category']) && !in_array($detail['product']['category']['name_cn'], $category)){
                        $category[] = $detail['product']['category']['name_cn'];
                    }
                }
            }
            $list[$key]['product_category'] = implode(', ', $category);
            $list[$key]['paid'] = 0;
            foreach($val['bill'] as $v){
                $list[$key]['paid'] += $v['amount'];
            }

            $list[$key]['paid'] = $list[$key]['paid'] == 0 ? $list[$key]['paid'] : $list[$key]['paid'] / $this->multiply;

        }


        $customer = db::name('customer')->alias('c')->join('customer_order o', 'c.id=o.customer_id')->field('c.*')->group('c.id')->order('c.id asc')->select()->toArray();
        foreach($customer as $key => $val){
            $customer[$key]['type'] = empty($val['type']) ? [] : explode(',', $val['type']);
        }

        $supplier_where['s.type'] = 'local';

        $supplier = db::name('supplier')->alias('s')->join('customer_order o', 's.id=o.supplier_id')->field('s.*')->group('s.id')->where($supplier_where)->select();


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'customer' => $customer,
            'supplier' => $supplier
        ]);
    }

    public function getAgent() {
        $param = $this->request->param();
        $agent = db::name('customer_order_agent')->alias('oa')
            ->field('oa.id, oa.agent_id, oa.commission, oa.commission_ratio, oa.commission_rate, oa.commission_tax, oa.to_commission, a.name, oa.profit')
            ->leftJoin('agent a', 'oa.agent_id=a.id')
            ->where(['oa.order_id' => $param['order_id']])->order('oa.id asc')->select()->toArray();
        foreach($agent as $key => $val){
            $agent[$key]['pop'] = false;
        }
        $this->success('', $agent);
    }

    public function detail() {
        $params = $this->request->param();
        $order = db::name('customer_order')->where(['id' => $params['id']])->find();
        $order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
        $customer = db::name('customer')->where(['id' => $order['customer_id']])->find();
        $supplier = db::name('supplier')->where(['id' => $order['supplier_id']])->find();
        $agent = db::name('customer_order_agent')->alias('oa')
            ->field('oa.id, oa.agent_id, oa.commission, oa.commission_ratio, oa.commission_rate, oa.commission_tax, oa.to_commission, a.name, oa.profit')
            ->leftJoin('agent a', 'oa.agent_id=a.id')
            ->where(['oa.order_id' => $order['id']])->order('oa.id asc')->select()->toArray();
        foreach($agent as $key => $val){
            $agent[$key]['pop'] = false;
        }
        if(empty($customer['corp_name_cn'])){
            $customer['corp_name_cn'] = $customer['corp_name_ko'];
        }

        $order['amount'] = empty($order['amount']) ? null : Numeral::numberFormat($order['amount'] / 100);
        $order['amount_usd'] = empty($order['amount_usd']) ? null : Numeral::numberFormat($order['amount_usd'] / 100);
        $order['cost'] = empty($order['cost']) ? null : Numeral::numberFormat($order['cost'] / 100);
        $order['drawback_amount'] = empty($order['drawback_amount']) ? null : Numeral::numberFormat($order['drawback_amount'] / 100);
        $order['logistics_amount'] = empty($order['logistics_amount']) ? null : Numeral::numberFormat($order['logistics_amount'] / 100);
        $order['profit'] = empty($order['profit']) ? null : Numeral::numberFormat($order['profit'] / 100);
        $order['tariff'] = empty($order['tariff']) ? null : Numeral::numberFormat($order['tariff']);
        $order['added'] = empty($order['added']) ? null : Numeral::numberFormat($order['added']);
        $order['order_images'] = empty($order['order_images']) ? '' : $order['order_images'];
//        $order['order_images'] = empty($order['order_images']) ? '' : 'http://localhost:8000' . $order['order_images'];
        $order['market_profit'] = empty($order['market_profit']) ? null : Numeral::numberFormat($order['market_profit'] / 100);
        $order['other_cost'] = empty($order['other_cost']) ? null : Numeral::numberFormat($order['other_cost'] / 100);
        $order['gross_profit'] = empty($order['gross_profit']) ? null : Numeral::numberFormat($order['gross_profit'] / 100);
        $order['net_profit'] = empty($order['net_profit']) ? null : Numeral::numberFormat($order['net_profit'] / 100);
        $order['sale_tax'] = empty($order['sale_tax']) ? null : Numeral::numberFormat($order['sale_tax'] / 100);
        $order['note'] = empty($order['note']) ? '' : html_entity_decode($order['note']);
        $this->success('', [
            'order' => $order,
            'customer' => $customer,
            'agent' => $agent,
            'supplier' => $supplier
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('数据不能为空'));
            }

            $product = empty($data['product']) ? [] : $data['product'];

            if(empty($data['customer_id'])) $this->error(__('请选择客户'));
//            if($this->filter['id'] != 2 && empty($data['supplier_id'])) $this->error(__('请选择供货商'));
            if(empty($data['type'])) $this->error(__('请选择订单类型'));
            $data['create_time'] = empty($data['create_time']) ? $this->timestamp : strtotime($data['create_time']);

            $result = false;
            $this->model->startTrans();
            try {
                $category_ids = [];
                foreach($product as $val){
                    if(!in_array($val['category_id'], $category_ids)) $category_ids[] = $val['category_id'];
                }
                $category = db::name('product_category')->whereIn('id', $category_ids)->select();
                $info = [];
                foreach($category as $val){
                    foreach($product as $v){
                        if($val['id'] == $v['category_id']){
                            $info['supplier_' . $val['supplier_id']]['product'][] = $v;
                            $info['supplier_' . $val['supplier_id']]['category'] = $val;
                        }
                    }
                }

                $order_today = db::name('customer_order')->whereDay('create_time', date('Y-m-d', $data['create_time']))->field('id, contract')->order('contract asc')->select();
                $contract = 'YN' . date('ymd', $data['create_time']);
//                print_r($order_today);die;
                if(count($order_today) == 1){
                    $contract .= '2';
                }else{
                    foreach($order_today as $val){
                        if(strlen($val['contract']) > 8){
                            $no = substr($val['contract'], -1) + 1;
                            $contract = 'YN' . date('ymd', $data['create_time']) . $no;
                        }
                    }
                }


                $last_order = db::name('customer_order')->order('batch_number desc')->find();
                $batch_number = empty($last_order['batch_number']) ? 1 : $last_order['batch_number'] + 1;



                if($data['type'][0] == '内销'){
                    $order_insert = [
                        'filter_id' => $this->filter['id'],
                        'customer_id' => $data['customer_id'],
                        'supplier_id' => $data['supplier_id'],
                        'out_trade_no' => Trade::generateTradeNoShort(),
                        'order_type' => $data['type'][0],
                        'trade_type' => $data['type'][1],
                        'create_time' => $data['create_time'],
                        'contract' => $contract,
                        'note' => empty($data['note']) ? null : $data['note'],
                        'deal_type' => empty($data['deal_type']) ? null : $data['deal_type'],
                        'shipment' => empty($data['shipment']) ? null : $data['shipment'],
                        'batch_number' => $batch_number
                    ];
                    $result = db::name('customer_order')->insertGetId($order_insert); // 写入订单
                }else{
                    if($info){
                        foreach($info as $key => $val){
                            $order_insert = [
                                'filter_id' => $this->filter['id'],
                                'customer_id' => $val['category']['customer_id'],
                                'supplier_id' => $val['category']['supplier_id'],
                                'out_trade_no' => Trade::generateTradeNoShort(),
                                'order_type' => $data['type'][0],
                                'trade_type' => $data['type'][1],
                                'create_time' => $data['create_time'],
                                'contract' => $contract,
                                'note' => empty($data['note']) ? null : $data['note'],
                                'deal_type' => empty($data['deal_type']) ? null : $data['deal_type'],
                                'shipment' => empty($data['shipment']) ? null : $data['shipment'],
                                'batch_number' => $batch_number
                            ];
                            $order_id = db::name('customer_order')->insertGetId($order_insert); // 写入订单


                            $order_detail = [];
                            foreach($val['product'] as $v){ // 记录订单详细内容
                                $order_detail[] = [
                                    'order_id' => $order_id,
                                    'product_id' => $v['id'],
                                    'quantity' => $v['number'] * $this->multiply,
                                ];
                            }
                            $result = db::name('customer_order_detail')->insertAll($order_detail);
                        }
                    }else{

                        $order_insert = [
                            'filter_id' => $this->filter['id'],
                            'customer_id' => $data['customer_id'],
                            'supplier_id' => empty($data['supplier_id']) ? 0 : $data['supplier_id'],
                            'out_trade_no' => Trade::generateTradeNoShort(),
                            'order_type' => $data['type'][0],
                            'trade_type' => $data['type'][1],
                            'create_time' => $data['create_time'],
                            'contract' => $contract,
                            'note' => empty($data['note']) ? null : $data['note'],
                            'deal_type' => empty($data['deal_type']) ? null : $data['deal_type'],
                            'shipment' => empty($data['shipment']) ? null : $data['shipment'],
                            'batch_number' => $batch_number
                        ];
                        $result = db::name('customer_order')->insertGetId($order_insert); // 写入订单
                    }


                }

                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }
        $this->error(__('Parameter error'));
    }


    public function edit(): void {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

//            print_r($data);die;

            $data['create_time'] = strtotime($data['create_time']);

            $data['type'] = empty($data['type']) ? null : $data['type'];
            if($data['type']){
                $data['order_type'] = $data['type'][0];
                $data['trade_type'] = $data['type'][1];
            }
            unset($data['type']);

            $order = db::name('customer_order')->where(['id' => $data['id']])->find();

            $product = $data['product'];
//            print_r($order);die;


            $result = false;
            $this->model->startTrans();

            try {

                db::name('customer_order_detail')->where(['order_id' => $row['id']])->delete();
                if(!empty($order['batch_number'])){
                    $unitary = [
                        'exchange' => empty($data['exchange']) ? null : $data['exchange'], // 汇率
                        'shipment' => empty($data['shipment']) ? null : $data['shipment'], // 运输方式
                        'order_type' => $data['order_type'],
                        'trade_type' => $data['trade_type'],
                    ];
                    db::name('customer_order')->where(['batch_number' => $order['batch_number']])->update($unitary);
                }



                $category_ids = [];
                foreach($product as $val){
                    if(!in_array($val['category_id'], $category_ids)) $category_ids[] = $val['category_id'];
                }
                $category = db::name('product_category')->whereIn('id', $category_ids)->select();
                $info = [];
                foreach($category as $val){
                    foreach($product as $v){
                        if($val['id'] == $v['category_id']){
                            $info['supplier_' . $val['supplier_id']]['product'][] = $v;
                            $info['supplier_' . $val['supplier_id']]['category'] = $val;
                        }
                    }
                }
//                print_r($info);die;
                $i = 0;
                if($info){
                    foreach($info as $key => $val){
                        $order_insert = [
                            'filter_id' => $this->filter['id'],
                            'customer_id' => $val['category']['customer_id'],
                            'supplier_id' => $val['category']['supplier_id'],
                            'out_trade_no' => $i == 0 ? $row['out_trade_no'] : Trade::generateTradeNoShort(),
                            'order_type' => $data['order_type'],
                            'trade_type' => $data['trade_type'],
                            'create_time' => $data['create_time'],
                            'contract' => $data['contract'],
                            'note' => empty($data['note']) ? null : $data['note'],
                            'deal_type' => empty($data['deal_type']) ? null : $data['deal_type'],
                            'shipment' => empty($data['shipment']) ? null : $data['shipment'],
                            'drawback_status' => empty($data['drawback_status']) ? null : $data['drawback_status'],
                            'invoice_no' => empty($data['invoice_no']) ? null : $data['invoice_no'],
                            'logistics_status' => empty($data['logistics_status']) ? null : $data['logistics_status'],
                            'bgd_no' => empty($data['bgd_no']) ? null : $data['bgd_no'],
                            'export_date' => empty($data['export_date']) ? null : $data['export_date'],
                        ];
                        if($i == 0){
                            $order_insert['contract'] = $row['contract'];
                            db::name('customer_order')->where(['id' => $row['id']])->update($order_insert); // 修改订单
                            $order_id = $row['id'];
                        }else{
                            $order_id = db::name('customer_order')->insertGetId($order_insert); // 写入订单
                        }
                        $order_detail = [];
                        foreach($val['product'] as $v){ // 记录订单详细内容
                            $order_detail[] = [
                                'order_id' => $order_id,
                                'product_id' => $v['id'],
                                'quantity' => $v['number'] * $this->multiply,
                            ];
                        }
                        $result = db::name('customer_order_detail')->insertAll($order_detail);
                        $i++;
                    }
                }else{
                    $order_update = [
                        'filter_id' => $this->filter['id'],
                        'customer_id' => $data['customer_id'],
                        'supplier_id' => $data['supplier_id'],
                        'order_type' => $data['order_type'],
                        'trade_type' => $data['trade_type'],
                        'contract' => $data['contract'],
                        'update_time' => $this->timestamp,
                        'deal_type' => empty($data['deal_type']) ? null : $data['deal_type'],
                        'shipment' => empty($data['shipment']) ? null : $data['shipment'],
                        'drawback_status' => empty($data['drawback_status']) ? null : $data['drawback_status'],
                        'invoice_no' => empty($data['invoice_no']) ? null : $data['invoice_no'],
                        'logistics_status' => empty($data['logistics_status']) ? null : $data['logistics_status'],
                        'bgd_no' => empty($data['bgd_no']) ? null : $data['bgd_no'],
                        'export_date' => empty($data['export_date']) ? null : $data['export_date'],
                        'create_time' => $data['create_time'],
                        'exchange' => empty($data['exchange']) ? null : $data['exchange']
                    ];
                    $result = $row->save($order_update);
//                    print_r($data);die;
                }


                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row = $row->toArray();


        $row['type'] = [$row['order_type'], $row['trade_type']];

        $row['create_time'] = date('Y-m-d', $row['create_time']);

        $product = db::name('customer_order_detail')->field('order_id, product_id, quantity')->where(['order_id' => $row['id']])->select();

        $row['product_ids'] = [];

        foreach($product as $key => $val){
            $info = db::name('product')->where(['id' => $val['product_id']])->find();
            $val['number'] = $val['quantity'] / $this->multiply;
            $product[$key] = array_merge($info, $val);
            $row['product_ids'][] = $val['product_id'];
        }
        $row['product'] = $product;



//        print_r($product);die;



        $this->success('', [
            'row' => $row
        ]);
    }

    public function editNote(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        if($this->request->has('field')){
            $field = $this->request->param('field');

            if($field == 'refunded'){
                $param['new_value'] *= 100;
            }

            $update = [
                $field => $param['new_value'],
                'update_time' => $this->timestamp
            ];
        }else{
            $update = [
                'note' => $param['new_value'],
                'update_time' => $this->timestamp
            ];
        }

        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
        print_r($param);die;
    }

    public function changeStatus(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'status' => $param['status'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }

    public function changeDrawbackStatus(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'drawback_status' => $param['drawback_status'],
            'update_time' => $this->timestamp,
            'optime' . $param['drawback_status'] => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function changeOrderType(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'order_type' => $param['order_type'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateAmount(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'amount' => $param['amount'] * 100,
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateTerm(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'term' => $param['term'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateTel(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'tel' => $param['tel'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateAddress(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'address' => $param['address'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateNote(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'note' => $param['note'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateAmountUsd(){
        $params = $this->request->param();
        $where = [
            'id' => $params['id']
        ];

        $exchange_record = db::name('exchange_record')->where(['date' => date('Y-m-d', $this->timestamp), 'name' => '美元'])->find();

        $update = [
            'amount_usd' => $params['amount_usd'] * 100,
            'update_time' => $this->timestamp
        ];
        $res_data = [
            'amount_usd' => $params['amount_usd'],
            'amount_cny' => -1
        ];
        if($exchange_record){
            $amount_cny = intval($params['amount_usd'] * ($exchange_record['mSellPri'] / 100));
            $update['amount'] = $amount_cny * 100;
            $res_data['amount_cny'] = $amount_cny;
        }
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success('', $res_data);
        }else{
            $this->error();
        }
    }
    public function updateProfit(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'profit' => $param['profit'] * 100,
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 佣金比率
     */

    public function updateCommissionRatio(){
        $param = $this->request->param();
        db::startTrans();
        try{
            $order_agent = db::name('customer_order_agent')->where(['id' => $param['id']])->find();
            $order = db::name('customer_order')->where(['id' => $order_agent['order_id']])->find();
            db::name('customer_order_agent')->where(['id' => $param['id']])->update([
                'update_time' => $this->timestamp,
                'commission_ratio' => $param['new_value']
            ]);

            $gross_profit = $order['gross_profit']; // 毛利
            $net_profit = $order['gross_profit']; // 纯利

            // 代理商
            $agent = db::name('customer_order_agent')->where(['order_id' => $order['id']])->select();
            foreach($agent as $val){
                $agent_update = [
                    'profit' => $gross_profit,
                    'update_time' => $this->timestamp
                ];
                // 计算代理商的佣金
                $commission_ratio = empty($val['commission_ratio']) ? 0 : $val['commission_ratio'] / 100; // 佣金比率
                $agent_update['commission'] = $gross_profit * $commission_ratio;
                // 计算代理商的佣金税金
                $commission_rate = empty($val['commission_rate']) ? 0 : $val['commission_rate'] / 100; // 佣金税率
                $agent_update['commission_tax'] = $agent_update['commission'] * $commission_rate;
                // 计算应付佣金
                $agent_update['to_commission'] = $agent_update['commission'] - $agent_update['commission_tax'];
                // 计算订单的纯利润
                $net_profit -= $agent_update['commission'];
                db::name('customer_order_agent')->where(['id' => $val['id']])->update($agent_update);
            }

            $update = [
                'update_time' => $this->timestamp,
                'gross_profit' => $gross_profit,
                'net_profit' => $net_profit,
            ];
            $result = db::name('customer_order')->where(['id' => $order['id']])->update($update);
            db::commit();
        }catch(\Exception $e){
            db::rollback();
//            $this->error($e->getMessage() . '---' . $e->getLine());
            $this->error($e->getMessage());
        }
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    public function updateCommissionRate(){
        $param = $this->request->param();
        db::startTrans();
        try{
            $order_agent = db::name('customer_order_agent')->where(['id' => $param['id']])->find();
            $order = db::name('customer_order')->where(['id' => $order_agent['order_id']])->find();
            db::name('customer_order_agent')->where(['id' => $param['id']])->update([
                'update_time' => $this->timestamp,
                'commission_rate' => $param['new_value']
            ]);

            $gross_profit = $order['gross_profit']; // 毛利
            $net_profit = $order['gross_profit']; // 纯利

            // 代理商
            $agent = db::name('customer_order_agent')->where(['order_id' => $order['id']])->select();
            foreach($agent as $val){
                $agent_update = [
                    'profit' => $gross_profit,
                    'update_time' => $this->timestamp
                ];
                // 计算代理商的佣金
                $commission_ratio = empty($val['commission_ratio']) ? 0 : $val['commission_ratio'] / 100; // 佣金比率
                $agent_update['commission'] = $gross_profit * $commission_ratio;
                // 计算代理商的佣金税金
                $commission_rate = empty($val['commission_rate']) ? 0 : $val['commission_rate'] / 100; // 佣金税率
                $agent_update['commission_tax'] = $agent_update['commission'] * $commission_rate;
                // 计算应付佣金
                $agent_update['to_commission'] = $agent_update['commission'] - $agent_update['commission_tax'];
                // 计算订单的纯利润
                $net_profit -= $agent_update['commission'];
                db::name('customer_order_agent')->where(['id' => $val['id']])->update($agent_update);
            }

            $update = [
                'update_time' => $this->timestamp,
                'gross_profit' => $gross_profit,
                'net_profit' => $net_profit,
            ];
            $result = db::name('customer_order')->where(['id' => $order['id']])->update($update);
            db::commit();
        }catch(\Exception $e){
            db::rollback();
            $this->error($e->getMessage() . '---' . $e->getLine());
            $this->error($e->getMessage());
        }
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 其他费用
     */
    public function updateOtherCost(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        db::startTrans();
        try{
            $order = db::name('customer_order')->where($where)->find();

            $other_cost = $param['other_cost'] * 100;


            $gross_profit = $order['market_profit'] - $order['sale_tax'] - $other_cost; // 毛利
            $net_profit = $gross_profit; // 纯利

            // 代理商
            $agent = db::name('customer_order_agent')->where(['order_id' => $order['id']])->select();
            foreach($agent as $val){
                $agent_update = [
                    'profit' => $gross_profit,
                    'update_time' => $this->timestamp
                ];
                // 计算代理商的佣金
                $commission_ratio = empty($val['commission_ratio']) ? 0 : $val['commission_ratio'] / 100; // 佣金比率
                $agent_update['commission'] = $gross_profit * $commission_ratio;
                // 计算代理商的佣金税金
                $commission_rate = empty($val['commission_rate']) ? 0 : $val['commission_rate'] / 100; // 佣金税率
                $agent_update['commission_tax'] = $agent_update['commission'] * $commission_rate;
                // 计算应付佣金
                $agent_update['to_commission'] = $agent_update['commission'] - $agent_update['commission_tax'];
                // 计算订单的纯利润
                $net_profit -= $agent_update['commission'];
                db::name('customer_order_agent')->where(['id' => $val['id']])->update($agent_update);
            }

            $update = [
                'other_cost' => $other_cost,
                'update_time' => $this->timestamp,
                'gross_profit' => $gross_profit,
                'net_profit' => $net_profit,
            ];
            $result = db::name('customer_order')->where($where)->update($update);
            db::commit();
        }catch(\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 销售税率
     */
    public function updateSaleRate(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        db::startTrans();
        try{
            $order = db::name('customer_order')->where($where)->find();

            $order['market_profit'] /= 100;

            $sale_tax = $order['market_profit'] * ($param['sale_rate'] / 100); // 销售税金

//            var_dump($sale_tax);die;

            $gross_profit = $order['market_profit'] - $sale_tax - ($order['other_cost'] / 100); // 毛利

            $net_profit = $gross_profit; // 纯利

            // 代理商
            $agent = db::name('customer_order_agent')->where(['order_id' => $order['id']])->select();
            foreach($agent as $val){
                $agent_update = [
                    'profit' => $gross_profit * 100,
                    'update_time' => $this->timestamp
                ];
                // 计算代理商的佣金
                $commission_ratio = empty($val['commission_ratio']) ? 0 : $val['commission_ratio'] / 100; // 佣金比率
                $agent_update['commission'] = $gross_profit * $commission_ratio;
                // 计算代理商的佣金税金
                $commission_rate = empty($val['commission_rate']) ? 0 : $val['commission_rate'] / 100; // 佣金税率
                $agent_update['commission_tax'] = $agent_update['commission'] * $commission_rate;
                // 计算应付佣金
                $agent_update['to_commission'] = $agent_update['commission'] - $agent_update['commission_tax'];
                // 计算订单的纯利润
                $net_profit -= $agent_update['commission'];

                $agent_update['commission'] *= 100;
                $agent_update['to_commission'] *= 100;
                db::name('customer_order_agent')->where(['id' => $val['id']])->update($agent_update);
            }

            $update = [
                'sale_rate' => $param['sale_rate'],
                'update_time' => $this->timestamp,
                'gross_profit' => $gross_profit * 100,
                'net_profit' => $net_profit * 100,
                'sale_tax' => $sale_tax * 100
            ];
            $result = db::name('customer_order')->where($where)->update($update);
            db::commit();
        }catch(\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 营销利润
     */
    public function updateMarketProfit(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];

        db::startTrans();
        try{
            $order = db::name('customer_order')->where($where)->find();

            /**
             * 计算毛利
             */
            if(empty($order['sale_rate'])){ // 销售税率是否为空
                $gross_profit = $param['market_profit'];
                $sale_tax = 0; // 销售税金
            }else{
                $sale_rate = $order['sale_rate'] / 100;
                $gross_profit = $param['market_profit'] - ($param['market_profit'] * ($sale_rate));
                $sale_tax = $param['market_profit'] * ($sale_rate);
            }

            // 减去其他费用 得出毛利
            $other_cost = empty($order['other_cost']) ? 0 : $order['other_cost'] / 100;
            $gross_profit = $gross_profit - $other_cost;
            $net_profit = $gross_profit;

            // 代理商
            $agent = db::name('customer_order_agent')->where(['order_id' => $order['id']])->select();
            foreach($agent as $val){
                $agent_update = [
                    'profit' => $gross_profit * 100,
                    'update_time' => $this->timestamp
                ];
                // 计算代理商的佣金
                $commission_ratio = empty($val['commission_ratio']) ? 0 : $val['commission_ratio'] / 100; // 佣金比率
                $agent_update['commission'] = $gross_profit * $commission_ratio;
                // 计算代理商的佣金税金
                $commission_rate = empty($val['commission_rate']) ? 0 : $val['commission_rate'] / 100; // 佣金税率
                $agent_update['commission_tax'] = $agent_update['commission'] * $commission_rate;
                // 计算应付佣金
                $agent_update['to_commission'] = $agent_update['commission'] - $agent_update['commission_tax'];

                // 计算订单的纯利润
                $net_profit -= $agent_update['commission'];
                $agent_update['to_commission'] *= 100;
                $agent_update['commission'] *= 100;
                db::name('customer_order_agent')->where(['id' => $val['id']])->update($agent_update);
            }

            $update = [
                'market_profit' => $param['market_profit'] * 100,
                'update_time' => $this->timestamp,
                'gross_profit' => $gross_profit * 100,
                'net_profit' => $net_profit * 100,
                'sale_tax' => $sale_tax * 100
            ];
            $result = db::name('customer_order')->where($where)->update($update);
            db::commit();
        }catch(\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }

        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateLogisticsAmount(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'logistics_amount' => $param['logistics_amount'] * 100,
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateAdded(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'added' => $param['added'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateTariff(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'tariff' => $param['tariff'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function updateDrawbackAmount(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'drawback_amount' => $param['drawback_amount'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }

    public function saveOrderImages() {
        $params = $this->request->param();
        $update = [
            'order_images' => $params['order_images'],
            'update_time' => $this->timestamp
        ];
//        print_r($update);die;
        $result = db::name('customer_order')->where(['id' => $params['id']])->update($update);
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 更新退税率
     */
    public function updateDrawbackRate(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];

        $order = db::name('customer_order')->where($where)->find();
        $cost = empty($order['cost']) ? 0 : floatval($order['cost'] / 100); // 货款
        $drawback_rate = empty($param['drawback_rate']) ? 0 : $param['drawback_rate']; // 退税率
        $drawback_amount = bcdiv(bcmul($cost, bcdiv($drawback_rate, '100', 2), 2), bcadd('1', bcdiv($drawback_rate, '100', 2), 2), 2); // 退税额



        $update = [
            'drawback_rate' => $param['drawback_rate'],
            'update_time' => $this->timestamp,
            'drawback_amount' => $drawback_amount * 100,
        ];
        if(empty($order['drawback_status'])){
            $update['drawback_status'] = 2;
            $update['optime2'] = $this->timestamp;
        }
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success('', [
                'drawback_amount' => Numeral::numberFormat($drawback_amount)
            ]);
        }else{
            $this->error();
        }
    }

    /**
     * 更新货款
     */
    public function updateCost(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $order = db::name('customer_order')->where($where)->find();
        $cost = empty($param['cost']) ? 0 : $param['cost']; // 货款
        $drawback_rate = empty($order['drawback_rate']) ? 0 : $order['drawback_rate']; // 退税率
        $drawback_amount = $cost / ( 1 + $drawback_rate / 100) * ($drawback_rate / 100); // 退税额
        $update = [
            'cost' => $param['cost'] * 100,
            'update_time' => $this->timestamp,
            'drawback_amount' => $drawback_amount * 100
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success('', [
                'drawback_amount' => Numeral::numberFormat($drawback_amount)
            ]);
        }else{
            $this->error();
        }
    }
    public function changeTradeType(){
        $param = $this->request->param();
        $where = [
            'id' => $param['id']
        ];
        $update = [
            'trade_type' => $param['trade_type'],
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where($where)->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 修改付款金额
     */
    public function updatePayAmount(){
        $param = $this->request->param();
        $row = db::name('customer_order')->where(['id' => $param['id']])->find();
        if($param['new_value'] * 100 > $row['amount']) $this->error(__('付款金额不能大于订单总价'));
        $update = [
            'pay_amount' => $param['new_value'] * 100,
            'update_time' => $this->timestamp
        ];
        $res = db::name('customer_order')->where(['id' => $param['id']])->update($update);
        if($res){
            $this->success();
        }else{
            $this->error();
        }
    }


    /**
     * 删除报价单
     */
    public function delQuotationFile(): void {
        $id = $this->request->param('id');
        $update = [
            'quotation_file' => null,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $id])->update($update);
        $this->success();
    }

    /**
     * 上传报价单
     */
    public function setQuotationFile(): void{
        $param = $this->request->post();
//        print_r($param);
        $quotation_file = json_encode($param['quotation_file']);
        $update = [
            'quotation_file' => $quotation_file,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $param['id']])->update($update);
        $this->success();
    }


    /**
     * 删除备注
     */
    public function delNote(){
        $param = $this->request->param();
        db::name('business_quotation_note')->where(['id' => $param['id']])->delete();
        $this->success();
    }

    /**
     * 添加备注
     */
    public function addNote(){
        $param = $this->request->param();
        $param['admin_id'] = $this->auth->id;
        $param['create_time'] = $this->timestamp;
        $note_id = db::name('business_quotation_note')->insertGetId($param);
        if($note_id){
            $this->success('', [
                'id' => $note_id,
                'content' => $param['content'],
                'admin' => [
                    'username' => $this->auth->username
                ]

            ]);
        }else{
            $this->error();
        }
    }

    /**
     * 隐藏报价
     */
    public function hideQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 1]);
        $this->success();
    }
    /**
     * 显示报价
     */
    public function showQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 0]);
        $this->success();
    }


































}